package com.ishansong.ticket.utils;

import com.google.common.collect.Lists;
import org.dozer.DozerBeanMapper;

import java.util.Collection;
import java.util.List;

/**
 * Bean Object Util based on dozer
 */
public class Beans {

    /**
     * dozer instance
     */
    private static DozerBeanMapper dozer = new DozerBeanMapper();
    /**
     * map object to target class
     * @param src source object
     * @param target target class
     * @param <T>
     * @return target class
     */
    public static <T> T map(Object src, Class<T> target) {
        return dozer.map(src, target);
    }

    /**
     * map collection object to target class collection
     * @param src source collection
     * @param target target class
     * @param <T>
     * @return target class list
     */
    public static <T> List<T> mapList(Collection src, Class<T> target) {
        List<T> targetList = Lists.newArrayListWithCapacity(src.size());
        for (Object sourceObject : src) {
            T targetObj = dozer.map(sourceObject, target);
            targetList.add(targetObj);
        }
        return targetList;
    }

    /**
     * deeply copy source object to target object
     * @param src source object
     * @param target target object
     */
    public static void copy(Object src, Object target) {
        dozer.map(src, target);
    }

    /**
     * deeply copy source object
     * @param src source object
     * @param clazz target class
     * @param <T>
     * @return new object of class
     */
    public static <T> T copyFrom(Object src, Class<T> clazz){
        try {
            T t = clazz.newInstance();
            dozer.map(src, t);
            return t;
        } catch (Exception e) {
            // ignore
            return null;
        }
    }
}